#!/bin/bash
# Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Make sure bluez is not running on the host. Kills it if it is running.
if [[ -z "$(service bluetooth status | grep "Status: \"Powering down\"")" ]];
then
    echo "Bluetooth have been found running on the host. We are going to disable it as it interferes with the test."
    service bluetooth stop
    timeout=5
    while [[ -z "$(service bluetooth status | grep "Status: \"Powering down\"")" ]] && (( timeout > 0 ))
    do
        sleep 1
        timeout=$(( $timeout - 1 ))
    done
    if (( timeout <= 0 ));
    then
        echo "bluetooth service failed to stop"
        exit 1
    fi
fi

# Default container settings. Can be overriden.
[[ -z ${CONTAINER_NAME} ]] && CONTAINER_NAME="ci_test"

if [[ -z "${CONTAINER_IMAGE_REGITRY}" ]];
then
    echo "No container registry specified. Please export CONTAINER_IMAGE_REGITRY"
    exit 1
fi
if [[ -z "${CONTAINER_IMAGE_NAME}" ]];
then
    echo "No container image specified. Please export CONTAINER_IMAGE_NAME"
    exit 1
fi

# Then create/start the container.
if [[ -z $(docker ps --all | grep ${CONTAINER_NAME}) ]]
then
    echo "creating a new instance"
    # Find the top level of the sdk repository and mount it to the containter,
    # assuming we are running this script from somewhere in the sdk repo.
    top_level=$(git rev-parse --show-toplevel)
    sudo docker run -it --cap-add=NET_ADMIN --net=host -v ${top_level}:/root/sdk --name ${CONTAINER_NAME} ${CONTAINER_IMAGE_REGITRY}/${CONTAINER_IMAGE_NAME} bash
else
    echo "resuming an old instance"
    docker start ${CONTAINER_NAME}
    docker attach ${CONTAINER_NAME}
fi
